package com.community.zhihuishequ.widget;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.support.annotation.NonNull;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.blankj.utilcode.util.ToastUtils;
import com.community.zhihuishequ.R;
import com.community.zhihuishequ.utils.DateUtils;
import com.community.zhihuishequ.view.base.BaseActivity;
import com.jzxiang.pickerview.TimePickerDialog;
import com.jzxiang.pickerview.data.Type;
import com.jzxiang.pickerview.listener.OnDateSetListener;

import org.bouncycastle.jce.provider.symmetric.TEA;

import java.text.SimpleDateFormat;
import java.util.Date;

public class CalendarDialog extends Dialog {

    public static final int DIALOG_ALL = 1;
    public static final int DIALOG_ENTER = 2;
    public static final int DIALOG_DEPARTURE = 3;

    public CalendarDialog(@NonNull Context context) {
        super(context, R.style.ios_dialog_style);
    }

    public interface Callback {
        void onConfirmContent(int type, String start, String endTime);
    }

    public static class Builder {
        private BaseActivity mContext;
        private CalendarDialog mIosDialog;
        private boolean mCancelable = true;
        private Callback callback;
        private boolean isRadioVisible = true;

        public Builder(BaseActivity context) {
            mContext = context;
        }

        public Builder setRadioVisible(boolean visible) {
            this.isRadioVisible = visible;
            return this;
        }

        public Builder setCancelable(boolean cancelable) {
            this.mCancelable = cancelable;
            return this;
        }

        public Builder setCallback(Callback callback) {
            this.callback = callback;
            return this;
        }

        public CalendarDialog create() {
            LayoutInflater inflater = LayoutInflater.from(mContext);
            View dialogView = inflater.inflate(R.layout.dialog_calendar, null);
            mIosDialog = new CalendarDialog(mContext);
            mIosDialog.setCancelable(mCancelable);

            LinearLayout llStartTime = dialogView.findViewById(R.id.ll_start_time);
            LinearLayout llEndTime = dialogView.findViewById(R.id.ll_end_time);
            final TextView tvStartTime = dialogView.findViewById(R.id.tv_start_time);
            final TextView tvEndTime = dialogView.findViewById(R.id.tv_end_time);
            final EditText etContent = dialogView.findViewById(R.id.et_content);
            RadioButton rbAll = dialogView.findViewById(R.id.rb_all);
            RadioButton rbEnter = dialogView.findViewById(R.id.rb_enter);
            RadioButton rbDeparture = dialogView.findViewById(R.id.rb_departure);
            final RadioGroup rbGroup = dialogView.findViewById(R.id.rb_group);
            Button btnSubmit = dialogView.findViewById(R.id.btn_submit);
            Button btnCancel = dialogView.findViewById(R.id.btn_cancel);

            rbGroup.setVisibility(isRadioVisible ? View.VISIBLE : View.GONE);

            llStartTime.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    showTimeDialog(tvStartTime);
                }
            });

            llEndTime.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    showTimeDialog(tvEndTime);
                }
            });

            //设置取消按钮
            btnCancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mIosDialog.dismiss();
                }
            });

            btnSubmit.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (callback != null) {
                        String startTime = tvStartTime.getText().toString();
                        String endTime = tvEndTime.getText().toString();
                        String contentString = etContent.getText().toString();
                        int type = 0;
                        switch (rbGroup.getCheckedRadioButtonId()) {
                            case R.id.rb_all:
                                type = DIALOG_ALL;
                                break;
                            case R.id.rb_enter:
                                type = DIALOG_ENTER;
                                break;
                            case R.id.rb_departure:
                                type = DIALOG_DEPARTURE;
                                break;
                            default:
                                break;
                        }
                        callback.onConfirmContent(type, startTime, endTime);
                    }
                    mIosDialog.dismiss();
                }
            });

            // 调整一下dialog的高度，如果高度充满屏幕不好看
            // 计算一下Dialog的高度,如果超过屏幕的4/5，则最大高度限制在4/5
            // 1.计算dialog的高度
            // TODO 测试发现的问题：如果放入一大串没有换行的文本到message区域，会导致测量出来的高度偏小，从而导致实际显示出来dialog充满了整个屏幕
            dialogView.measure(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            int dialogHeight = dialogView.getMeasuredHeight();
            // 2.得到屏幕高度
            WindowManager wm = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
            DisplayMetrics metrics = new DisplayMetrics();
            wm.getDefaultDisplay().getMetrics(metrics);
            int maxHeight = (int) (metrics.heightPixels * 0.8);
            ViewGroup.LayoutParams dialogParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT);
            // 3.如果高度超限，限制dialog的高度
            if (dialogHeight >= maxHeight) {
                dialogParams.height = maxHeight;
            }
            mIosDialog.setContentView(dialogView, dialogParams);

            return mIosDialog;
        }

        public CalendarDialog show() {
            mIosDialog = create();
            mIosDialog.show();
            return mIosDialog;
        }

        private void showTimeDialog(final TextView textView) {
            long tenYears = 20L * 365 * 1000 * 60 * 60 * 24L;
            TimePickerDialog timePickerDialog = new TimePickerDialog.Builder()
                    .setCancelStringId("取消")
                    .setSureStringId("选择")
                    .setTitleStringId("请选择时间")
                    .setYearText("年")
                    .setMonthText("月")
                    .setDayText("日")
                    .setHourText("时")
                    .setMinuteText("分")
                    .setCyclic(false)
                    .setMinMillseconds(System.currentTimeMillis() - tenYears)
                    .setMaxMillseconds(System.currentTimeMillis() + tenYears)
                    .setCurrentMillseconds(System.currentTimeMillis())
                    .setThemeColor(mContext.getResources().getColor(R.color.colorPrimary))
                    .setType(Type.ALL)
                    .setWheelItemTextNormalColor(mContext.getResources().getColor(R.color.timetimepicker_default_text_color))
                    .setWheelItemTextSelectorColor(mContext.getResources().getColor(R.color.colorPrimary))
                    .setWheelItemTextSize(14)
                    .setCallBack(new OnDateSetListener() {
                        @Override
                        public void onDateSet(TimePickerDialog timePickerDialog, long millseconds) {
                            SimpleDateFormat sdr = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                            String time = sdr.format(millseconds);
                            textView.setText(time);
                        }
                    })
                    .build();
            timePickerDialog.show(mContext.getSupportFragmentManager(), "all");
        }
    }
}
